<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生成学生数据</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 12px 24px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 20px 0;
            cursor: pointer;
            border-radius: 4px;
        }
        button:hover {
            background-color: #45a049;
        }
        #log {
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            max-height: 500px;
            overflow-y: auto;
            font-family: monospace;
            white-space: pre-wrap;
        }
        .error {
            color: #d32f2f;
        }
        .success {
            color: #388e3c;
        }
    </style>
</head>
<body>
    <h1>为每个班级生成15名学生数据</h1>
    <p>点击下方按钮开始生成学生数据。此操作会为系统中的每个班级添加15名学生，确保学生的阶段和学院与所属班级一致。</p>
    <button id="generateBtn">开始生成学生数据</button>
    <div id="log"></div>

    <script type="module">
        import { DataService } from './src/shared/dataService.js';
        
        const logElement = document.getElementById('log');
        const generateBtn = document.getElementById('generateBtn');
        
        // 日志输出函数
        function log(message, type = 'info') {
            const logEntry = document.createElement('div');
            logEntry.textContent = message;
            logEntry.className = type;
            logElement.appendChild(logEntry);
            logElement.scrollTop = logElement.scrollHeight;
        }
        
        // 中文字符生成辅助函数
        function generateChineseName() {
            const surnames = ['王', '李', '张', '刘', '陈', '杨', '赵', '黄', '周', '吴', '徐', '孙', '胡', '朱', '高', '林', '何', '郭', '马', '罗'];
            const names = ['伟', '芳', '娜', '秀英', '敏', '静', '强', '磊', '军', '洋', '勇', '艳', '杰', '秀英', '娟', '涛', '明', '超', '秀兰', '霞'];
            
            const surname = surnames[Math.floor(Math.random() * surnames.length)];
            // 70%概率双字名，30%概率单字名
            const nameLength = Math.random() > 0.3 ? 2 : 1;
            
            let givenName = '';
            for (let i = 0; i < nameLength; i++) {
                givenName += names[Math.floor(Math.random() * names.length)];
            }
            
            return surname + givenName;
        }
        
        // 生成学号的辅助函数
        function generateStudentId(classInfo, index) {
            // 假设当前年份
            const currentYear = new Date().getFullYear();
            
            // 根据阶段确定入学年份偏移
            let yearOffset = 0;
            if (classInfo.stage.includes('freshman') || classInfo.stage === 'freshman') {
                yearOffset = 0;
            } else if (classInfo.stage.includes('sophomore') || classInfo.stage === 'sophomore') {
                yearOffset = 1;
            } else if (classInfo.stage.includes('junior') || classInfo.stage === 'junior' || classInfo.stage.includes('shixun')) {
                yearOffset = 2;
            } else if (classInfo.stage.includes('zhuangao')) {
                // 专高阶段可能对应不同的年份，这里简单处理
                yearOffset = 1;
            }
            
            // 生成入学年份
            const admissionYear = currentYear - yearOffset;
            
            // 学院代码（简化版）
            const academyCode = {
                'computer': '01',
                'electronics': '02',
                'mechanical': '03',
                'civil': '04',
                'chemistry': '05',
                'biology': '06',
                'arts': '07',
                'business': '08'
            }[classInfo.academy] || '00';
            
            // 班级序号（从班级名称中提取或随机生成）
            const classNumber = classInfo.name.match(/\d+/) ? 
                classInfo.name.match(/\d+/)[0].padStart(2, '0') : 
                Math.floor(Math.random() * 99).toString().padStart(2, '0');
            
            // 学生序号
            const studentNumber = (index + 1).toString().padStart(2, '0');
            
            return `${admissionYear}${academyCode}${classNumber}${studentNumber}`;
        }
        
        // 生成学生数据的主函数
        async function generateStudents() {
            generateBtn.disabled = true;
            log('开始生成学生数据...');
            
            try {
                const dataService = new DataService();
                
                // 获取所有班级
                const classes = await dataService.getClasses();
                log(`找到 ${classes.length} 个班级`);
                
                let totalStudentsGenerated = 0;
                
                // 为每个班级生成学生
                for (const cls of classes) {
                    log(`正在为班级 ${cls.name} (${cls.stage}) 生成学生...`);
                    
                    // 获取当前班级已有的学生数量
                    const existingStudents = await dataService.getStudents();
                    const currentClassStudents = existingStudents.filter(s => s.classId === cls.id);
                    
                    // 如果已有15名或更多学生，则跳过
                    if (currentClassStudents.length >= 15) {
                        log(`班级 ${cls.name} 已有 ${currentClassStudents.length} 名学生，跳过生成`);
                        continue;
                    }
                    
                    // 需要生成的学生数量
                    const studentsToGenerate = 15 - currentClassStudents.length;
                    log(`需要为班级 ${cls.name} 生成 ${studentsToGenerate} 名学生`);
                    
                    let classStudentsGenerated = 0;
                    
                    // 生成新学生
                    for (let i = 0; i < studentsToGenerate; i++) {
                        const gender = Math.random() > 0.5 ? 'male' : 'female';
                        const studentId = generateStudentId(cls, i + currentClassStudents.length);
                        
                        // 生成出生日期（18-22岁之间）
                        const birthYear = new Date().getFullYear() - 18 - Math.floor(Math.random() * 5);
                        const birthMonth = Math.floor(Math.random() * 12) + 1;
                        const birthDay = Math.floor(Math.random() * 28) + 1;
                        const dateOfBirth = `${birthYear}-${birthMonth.toString().padStart(2, '0')}-${birthDay.toString().padStart(2, '0')}`;
                        
                        // 生成入学日期
                        const admissionYear = new Date().getFullYear();
                        const admissionDate = `${admissionYear}-09-01`;
                        
                        // 生成电话号码
                        const phoneNumber = `13${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}`;
                        
                        // 生成邮箱
                        const email = `${studentId}@student.example.com`;
                        
                        // 生成地址
                        const provinces = ['北京市', '上海市', '广东省', '江苏省', '浙江省', '四川省', '湖北省', '湖南省', '山东省', '河南省'];
                        const cities = ['市辖区', '市', '地区', '自治州'];
                        const districts = ['区', '县', '县级市'];
                        const streets = ['街道', '路', '大道'];
                        
                        const province = provinces[Math.floor(Math.random() * provinces.length)];
                        const city = cities[Math.floor(Math.random() * cities.length)];
                        const district = districts[Math.floor(Math.random() * districts.length)];
                        const street = streets[Math.floor(Math.random() * streets.length)];
                        
                        const address = `${province}${city}${district}${street}${Math.floor(Math.random() * 1000)}号`;
                        
                        // 创建学生数据，确保阶段和学院与班级一致
                        const studentData = {
                            name: generateChineseName(),
                            studentId: studentId,
                            gender: gender,
                            stage: cls.stage, // 阶段与班级一致
                            academy: cls.academy, // 学院与班级一致
                            classId: cls.id,
                            dateOfBirth: dateOfBirth,
                            admissionDate: admissionDate,
                            phoneNumber: phoneNumber,
                            email: email,
                            address: address,
                            status: 'active'
                        };
                        
                        try {
                            await dataService.createStudent(studentData);
                            log(`成功创建学生: ${studentData.name} (${studentData.studentId})`, 'success');
                            classStudentsGenerated++;
                            totalStudentsGenerated++;
                        } catch (error) {
                            log(`创建学生失败: ${error.message}`, 'error');
                        }
                    }
                    
                    log(`班级 ${cls.name} 生成完成，新增 ${classStudentsGenerated} 名学生`);
                }
                
                log(`所有班级学生生成完成！总共生成了 ${totalStudentsGenerated} 名学生。`, 'success');
                log('请刷新学生管理页面查看生成的学生数据。');
            } catch (error) {
                log(`执行过程中出错: ${error.message}`, 'error');
            } finally {
                generateBtn.disabled = false;
            }
        }
        
        // 绑定按钮点击事件
        generateBtn.addEventListener('click', generateStudents);
    </script>
</body>
</html>